<template>
    <view class="pages-technician">
        <!-- <back></back> -->
        <fixed :initHeight="configInfo.coach_format">
            <uni-nav-bar
                :fixed="false"
                :shadow="false"
                :statusBar="true"
                :onlyLeft="true"
                :color="`#fff`"
                :backgroundColor="primaryColor"
            >
                <view @tap.stop="toChooseLocation" class="map-info flex-y-center" slot="left">
                    <view class="flex-y-center c-base">
                        <!-- 改 -->
                        <view style="margin-right: 10rpx" @click="goService">
                            <image
                                style="width: 40rpx; height: 40rpx"
                                src="../static/tab/homey.png"
                                mode="scaleToFill"
                            >
                            </image>
                        </view>
                        <i class="iconfont iconjuli mr-sm"></i>
                        <view class="map-text max-400 ellipsis">
                            {{
                                location && location.address
                                    ? location.address
                                    : isLoad
                                    ? "定位失败"
                                    : "定位中..."
                            }}
                        </view>
                        <i class="iconfont icon-down"></i>
                    </view>
                </view>
            </uni-nav-bar>
            <view
                class="fix-info fill-body rel"
                :style="{ height: configInfo.coach_format == 2 ? '124rpx' : '' }"
            >
                <view class="space-top abs" :style="{ background: primaryColor }"></view>
                <view
                    class="search-info fill-base pt-lg pl-lg pr-lg abs"
                    :class="[{ 'pb-md': configInfo.coach_format != 2 }]"
                >
                    <view
                        class="flex-center"
                        :class="[
                            { 'pb-md': configInfo.coach_format != 2 },
                            { 'pb-lg': configInfo.coach_format == 2 },
                        ]"
                    >
                        <view class="city-info">
                            <picker
                                @change="pickerChange($event)"
                                :value="cityIndex"
                                :range="cityList"
                                range-key="title"
                            >
                                <view class="city-info flex-y-center">
                                    <view>
                                        <block v-if="cityList && cityList.length > 0">
                                            {{
                                                cityIndex === -1
                                                    ? "未知"
                                                    : cityList[cityIndex].title.length > 3
                                                    ? cityList[cityIndex].title.substring(0, 3) +
                                                      "..."
                                                    : cityList[cityIndex].title
                                            }}
                                        </block>
                                        <block v-else>请选择</block>
                                    </view>
                                    <i class="iconfont iconshaixuanxia-1 ml-sm"></i>
                                </view>
                            </picker>
                        </view>
                        <view class="flex-1">
                            <search
                                @input="toSearch"
                                type="input"
                                :keyword="param.coach_name"
                                :padding="0"
                                :radius="30"
                                backgroundColor="#F0F0F0"
                                :placeholder="'请输入' + $t('action.attendantName') + '姓名'"
                            >
                            </search>
                        </view>
                    </view>
                    <block v-if="configInfo.coach_format != 2">
                        <tab
                            @change="handerTabChange"
                            :list="tabList"
                            :activeIndex="activeIndex * 1"
                            :activeColor="primaryColor"
                            width="22%"
                            height="90rpx"
                            fontSize="28rpx"
                        ></tab>
                        <view class="shaixuan" @tap.stop="screen">
                            <view>tu</view>
                            <view>筛选</view>
                        </view>
                    </block>
                </view>
            </view>
        </fixed>

        <block v-if="pageActive && list.data && list.data.length > 0">
            <view class="mt-md ml-md mr-md" v-for="(item, index) in list.data" :key="index">
                <technician-list-item
                    @comment="toShowPopup(index, 'message')"
                    @collect="toCollect(index)"
                    @order="toShowPopup(index, 'technician')"
                    :info="item"
                >
                </technician-list-item>
            </view>
        </block>

        <!-- #ifdef H5 -->
        <load-more
            :noMore="list.current_page >= list.last_page && list.data.length > 0"
            :loading="loading"
            v-if="loading"
        >
        </load-more>
        <abnor v-if="!loading && list.data.length <= 0 && list.current_page == 1"></abnor>
        <!-- #endif -->
        <!-- #ifndef H5 -->
        <load-more
            :noMore="list.current_page >= list.last_page && list.data.length > 0 && location.lng"
            :loading="loading"
            v-if="loading"
        >
        </load-more>
        <abnor
            v-if="!loading && list.data.length <= 0 && list.current_page == 1 && location.lng"
        ></abnor>
        <abnor
            @confirm="toOpenLocation"
            :tip="[{ text: '定位失败，请开启地理位置授权后刷新页面重试~', color: 0 }]"
            :button="[{ text: '开启定位', type: 'confirm' }]"
            btnSize=""
            v-if="!loading && !location.lng"
        >
        </abnor>
        <!-- #endif -->

        <view class="space-footer"></view>

        <technician-list-popup ref="technician_list_popup"></technician-list-popup>

        <uni-popup ref="choose_city_item" type="top" :custom="true" :zIndex="999">
            <view :style="{ height: configInfo.navBarHeight + 8 + 'px' }"></view>
            <view class="choose-city-popup rel">
                <image
                    class="city-img"
                    src="https://lbqny.migugu.com/admin/anmo/technician/no_city.png"
                ></image>
                <view class="text f-paragraph c-base abs">
                    很抱歉,该城市未开通, 点击左上角切换其他城市下单服务
                </view>
                <view class="flex-between">
                    <view></view>
                    <view
                        @tap.stop="$refs.choose_city_item.close()"
                        class="item-btn flex-center f-paragraph c-title text-bold radius"
                        >知道了</view
                    >
                </view>
            </view>
        </uni-popup>

        <view :style="{ height: `${configInfo.tabbarHeight}px` }"></view>
        <tabbar :cur="2"></tabbar>

        <!-- #ifdef APP-PLUS -->
        <login-info></login-info>
        <!-- #endif -->
        <view v-if="flag" class="shaixuan_box_zzc" @tap.stop="close"></view>
        <view v-if="flag" class="shaixuan_box">
            <view class="con">
                <view class="sex">
                    <view style="margin-bottom: 20rpx">性别</view>
                    <view style="display: flex; flex-direction: row; justify-content: space-around">
                        <view
                            :class="info.sex === item.index ? 'sex_bj xzzt' : 'sex_bj'"
                            v-for="(item, index) in sexInfo"
                            :key="index"
                            @tap.stop="xzsex(index)"
                        >
                            {{ item.value }}
                        </view>
                    </view>
                </view>
                <view class="age">
                    <view style="margin-bottom: 20rpx">年龄段</view>
                    <view
                        style="
                            display: flex;
                            flex-direction: row;
                            flex-wrap: wrap;
                            justify-content: space-around;
                        "
                    >
                        <view
                            :class="info.age === item.index ? 'age_bj xzzt' : 'age_bj'"
                            v-for="(item, index) in ageInfo"
                            :key="index"
                            @tap.stop="xzage(index)"
                        >
                            {{ item.value }}
                        </view>
                    </view>
                </view>
                <view class="zh">
                    <view style="margin-bottom: 20rpx">综合</view>
                    <view
                        style="
                            display: flex;
                            flex-direction: row;
                            flex-wrap: wrap;
                            justify-content: space-between;
                        "
                    >
                        <view
                            :class="info.zh === item.index ? 'zh_bj xzzt' : 'zh_bj'"
                            v-for="(item, index) in zhInfo"
                            :key="index"
                            @tap.stop="xzzh(index)"
                        >
                            {{ item.value }}
                        </view>
                    </view>
                </view>
                <view class="btn">
                    <view @tap.stop="() => handerTabChange2(info)">确定</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import siteInfo from "@/siteinfo.js";
import tabbar from "@/components/tabbar.vue";
import technicianListItem from "@/components/technician-list-item.vue";
import technicianListPopup from "@/components/technician-list-popup.vue";
export default {
    components: {
        tabbar,
        technicianListItem,
        technicianListPopup,
    },
    data() {
        return {
            isLoad: false,
            options: {},
            loading: true,
            lockTap: false,
            flag: false,
            sexInfo: [
                { value: "男", index: 0 },
                { value: "女", index: 1 },
            ],
            ageInfo: [
                { value: "18-22", index: 0 },
                { value: "23-28", index: 1 },
                { value: "29-32", index: 2 },
                { value: "33-38", index: 3 },
                { value: "39-45", index: 4 },
                { value: "45以上", index: 5 },
            ],
            zhInfo: [
                { value: "距离优先", index: 0 },
                { value: "单量", index: 1 },
                { value: "好评", index: 2 },
            ],
            info: {
                sex: 1,
                age: 1,
                zh: 1,
            },
        };
    },
    computed: mapState({
        pageActive: (state) => state.technician.pageActive,
        haveOperItem: (state) => state.technician.haveOperItem,
        cityId: (state) => state.technician.cityId,
        cityIndex: (state) => state.technician.cityIndex,
        cityList: (state) => state.technician.cityList,
        activeIndex: (state) => state.technician.activeIndex,
        tabList: (state) => state.technician.tabList,
        param: (state) => state.technician.param,
        list: (state) => state.technician.list,
        primaryColor: (state) => state.config.configInfo.primaryColor,
        subColor: (state) => state.config.configInfo.subColor,
        configInfo: (state) => state.config.configInfo,
        loginType: (state) => state.user.loginType,
        userInfo: (state) => state.user.userInfo,
        location: (state) => state.user.location,
        isGzhLogin: (state) => state.user.isGzhLogin,
        haveShieldOper: (state) => state.user.haveShieldOper,
    }),
    async onLoad(options) {
        this.options = options;
        let { pid = 0, city_id = 0, coach_id = 0, coach_name = "" } = options;

        let param = this.$util.deepCopy(this.param);
        param.coach_id = coach_id;
        param.coach_name = coach_name;
        this.updateTechnicianItem({
            key: "param",
            val: param,
        });

        if (coach_id) {
            this.updateTechnicianItem({
                key: "cityId",
                val: city_id,
            });
        }
        // #ifdef H5
        uni.setNavigationBarTitle({
            title: this.$t("action.attendantName"),
        });
        // #endif
        // #ifndef H5

        this.$util.showLoading();
        // #endif

        let { data = [] } = this.list;
        let city_refresh = data.length == 0 || data[0].city_id != this.cityId;
        if (this.pageActive && (!coach_id || !pid) && !city_refresh) {
            this.isLoad = true;
            this.loading = false;
            this.$util.hideAll();
            return;
        }
        await this.initIndex();
    },
    async onShow() {
        // #ifdef H5
        if (this.$jweixin.isWechat()) {
            await this.$jweixin.initJssdk();
            this.toAppShare();
        }
        // #endif
        if (this.haveShieldOper == 2 || this.haveOperItem) {
            this.initIndex();
            this.updateUserItem({
                key: "haveShieldOper",
                val: 0,
            });
            this.updateTechnicianItem({
                key: "haveOperItem",
                val: false,
            });
        }
    },
    onPullDownRefresh() {
        // #ifndef APP-PLUS
        uni.showNavigationBarLoading();
        // #endif
        this.initRefresh();
        uni.stopPullDownRefresh();
    },
    onReachBottom() {
        if (this.list.current_page >= this.list.last_page || this.loading) return;
        this.loading = true;
        this.getList(this.param.page + 1);
    },
    onShareAppMessage(e) {
        let { id: pid = 0 } = this.userInfo;
        let path = `/pages/technician?pid=${pid}`;
        this.$util.log(path);
        return {
            title: "",
            imageUrl: "",
            path,
        };
    },
    methods: {
        ...mapActions(["getConfigInfo", "getUserInfo", "getCityList", "getServiceCoachList"]),
        ...mapMutations(["updateUserItem", "updateTechnicianItem"]),
        async initIndex(refresh = false) {
            // #ifdef H5
            if (!refresh && this.$jweixin.isWechat()) {
                await this.$jweixin.initJssdk();
                this.toAppShare();
            }
            // #endif
            let { pid = 0 } = this.options;
            let { isGzhLogin } = this;
            let { id: uid = 0 } = this.userInfo;
            if (pid && !uid) {
                // #ifdef H5
                if (isGzhLogin) {
                    setTimeout(() => {
                        this.getUserInfo();
                    }, 1000);
                } else {
                    this.getUserInfo();
                }
                // #endif
                // #ifndef H5
                await this.getUserInfo();
                // #endif
            }

            if (!this.configInfo.id || refresh) {
                await this.getConfigInfo();
            }
            await this.getList(1, true);
            this.updateTechnicianItem({
                key: "pageActive",
                val: true,
            });
        },
        initRefresh() {
            this.param.page = 1;
            this.initIndex(true);
        },
        toAppShare() {
            let { id: pid = 0 } = this.userInfo;
            let title = this.$t("action.attendantName");
            let { siteroot } = siteInfo;
            let url = siteroot.split("/index.php")[0];
            let href = `${url}/h5/#/pages/technician?pid=${pid}`;
            let imageUrl = "";
            this.$jweixin.wxReady(() => {
                this.$jweixin.showOptionMenu();
                this.$jweixin.shareAppMessage(title, "", href, imageUrl);
                this.$jweixin.shareTimelineMessage(title, href, imageUrl);
            });
        },
        pickerChange(e, val) {
            let ind = e.target.value;
            this.updateTechnicianItem({
                key: "cityIndex",
                val: ind,
            });
            this.updateTechnicianItem({
                key: "cityId",
                val: this.cityList[ind].id,
            });
            this.getList(1);
        },
        toOpenLocation() {
            this.$util.checkAuth({
                type: "userLocation",
            });
            // #ifdef APP-PLUS
            uni.getSystemInfo({
                success: (sys) => {
                    if (sys.platform == "ios") {
                        plus.runtime.openURL("app-settings://");
                    } else {
                        var main = plus.android.runtimeMainActivity();
                        var Intent = plus.android.importClass("android.content.Intent");
                        //可能应该直接进入应用列表的权限设置？=> android.settings.APPLICATION_SETTINGS
                        var mIntent = new Intent("android.settings.LOCATION_SOURCE_SETTINGS");
                        main.startActivity(mIntent);
                    }
                },
            });
            // #endif
        },
        toSearch(val) {
            let param = this.$util.deepCopy(this.param);
            param.coach_id = "";
            param.coach_name = val;
            this.updateTechnicianItem({
                key: "param",
                val: param,
            });
            this.getList(1);
        },
        // 选择地区
        async toChooseLocation(e) {
            await this.$util.checkAuth({
                type: "userLocation",
            });
            let { lat: locaLat = "", lng: locaLng = "" } = this.location;
            let param = {};
            if (!locaLat && !locaLng) {
                // #ifdef H5
                if (this.$jweixin.isWechat()) {
                    this.$util.showLoading();
                    await this.$jweixin.wxReady2();
                    let { latitude, longitude } = await this.$jweixin.getWxLocation();
                    locaLat = latitude;
                    locaLng = longitude;
                }
                // #endif
                // #ifdef APP-PLUS
                let location = await this.$util.getBmapLocation();
                locaLat = location.lat;
                locaLng = location.lng;
                // #endif
            }

            // #ifndef MP-WEIXIN
            param = {
                latitude: locaLat,
                longitude: locaLng,
            };
            // #endif
            let [
                ,
                {
                    address = "",
                    longitude: lng,
                    latitude: lat,
                    province = "",
                    city = "",
                    district = "",
                },
            ] = await uni.chooseLocation(param);
            if (!lng) return;
            let location = {
                lng,
                lat,
                address,
                province,
                city,
                district,
            };
            this.updateUserItem({
                key: "location",
                val: location,
            });
            await this.getList(1, true, 1);
        },
        async getList(page = 0, refresh = false, change = 0) {
            if (page) {
                let param = this.$util.deepCopy(this.param);
                param.page = page;
                this.updateTechnicianItem({
                    key: "param",
                    val: param,
                });
            }
            let { location } = this;
            if (!location.lat || (location.lat && location.address == "定位失败")) {
                // #ifdef H5
                if (this.$jweixin.isWechat()) {
                    this.$util.showLoading();
                    // await this.$jweixin.initJssdk();
                    await this.$jweixin.wxReady2();
                    let { lat = "", lng = "" } = location;
                    if (!lat && !lng) {
                        let { latitude, longitude } = await this.$jweixin.getWxLocation();
                        lat = latitude;
                        lng = longitude;
                        location = {
                            lng,
                            lat,
                            address: "定位失败",
                            province: "",
                            city: "",
                            district: "",
                        };
                    }
                    if (lat && lng) {
                        let key = `${lat},${lng}`;
                        let data = await this.$api.base.getMapInfo({
                            location: key,
                        });
                        let { status, result } = JSON.parse(data);
                        if (status == 0) {
                            let { address, address_component } = result;
                            let { province, city, district } = address_component;
                            location = {
                                lng,
                                lat,
                                address,
                                province,
                                city,
                                district,
                            };
                        }
                    }
                }
                // #endif
                // #ifndef H5
                location = await this.$util.getBmapLocation();
                // #endif
                this.updateUserItem({
                    key: "location",
                    val: location,
                });
            }
            let { lng = 0, lat = 0 } = location;

            if (refresh) {
                await this.getCityList({
                    lng,
                    lat,
                    change,
                });
            }

            let {
                list: oldList,
                tabList,
                activeIndex,
                cityList,
                cityIndex,
                cityId: city_id,
            } = this;

            let param = this.$util.deepCopy(this.param);

            let ind = cityList.findIndex((item) => {
                return item.id == city_id;
            });

            if (ind == -1) {
                this.$refs.choose_city_item.open();
                this.loading = false;
                this.$util.hideAll();
                this.updateTechnicianItem({
                    key: "list",
                    val: {
                        data: [],
                        last_page: 1,
                        current_page: 1,
                    },
                });
                return;
            }

            city_id = ind == -1 ? 0 : city_id;
            cityIndex = ind == -1 ? 0 : ind;

            this.updateTechnicianItem({
                key: "cityIndex",
                val: cityIndex,
            });

            this.updateTechnicianItem({
                key: "cityId",
                val: city_id,
            });

            param = Object.assign({}, param, {
                lng,
                lat,
                city_id,
            });

            let { coach_format = 1 } = this.configInfo;

            if (coach_format == 1) {
                console.log(tabList, "tabList");
                console.log(activeIndex, "activeIndex");
                param.type = tabList[activeIndex].id;
            }

            if (change === 9) {
                param.age = this.info.age;
                param.sex = this.info.sex;
                param.zh = this.info.zh;
            }

            await this.getServiceCoachList(param);
            this.loading = false;
            this.$util.hideAll();
        },
        handerTabChange(index, info) {
            this.updateTechnicianItem({
                key: "activeIndex",
                val: index,
            });

            this.$util.showLoading();
            uni.pageScrollTo({
                scrollTop: 0,
            });
            this.getList(1);
        },
        handerTabChange2(info) {
            this.$util.showLoading();
            uni.pageScrollTo({
                scrollTop: 0,
            });
            this.getList(1, true, 9);
            this.close();
        },
        async toShowPopup(index, key) {
            this.$refs.technician_list_popup.toShowPopup(this.list.data[index], key);
        },
        async toCollect(index) {
            let { id, is_collect, collect_num } = this.list.data[index];
            let methodModel = is_collect ? "delCollect" : "addCollect";
            await this.$api.mine[methodModel]({
                coach_id: id,
            });
            this.$util.showToast({
                title: is_collect ? "取消成功" : "收藏成功",
            });
            this.list.data[index].is_collect = is_collect == 1 ? 0 : 1;
            this.list.data[index].collect_num = is_collect == 1 ? collect_num - 1 : collect_num + 1;
        },
        // 点击图标跳转首页
        goService() {
            this.$util.goUrl({
                url: `/pages/service`,
            });
        },
        screen() {
            this.flag = true;
        },
        close() {
            this.flag = false;
        },
        xzsex(index) {
            this.info.sex = index;
        },
        xzage(index) {
            this.info.age = index;
        },
        xzzh(index) {
            this.info.zh = index;
        },
    },
};
</script>

<style lang="scss">
.shaixuan {
    position: absolute;
    top: 62%;
    right: 2%;
    width: 95rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

.shaixuan_box {
    position: fixed;
    top: 0;
    right: 0;
    width: 60%;
    height: 100%;
    background-color: #fff;
    z-index: 999;
}

.shaixuan_box_zzc {
    position: fixed;
    top: 0;
    left: 0;
    width: 40%;
    height: 100%;
    background-color: $uni-bg-color-mask;
    z-index: 999;
}

.con {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 7%;
    right: 0;
}

.sex {
    width: 100%;
    height: 10%;
    padding: 20rpx;
}

.sex_bj {
    width: 40%;
    background-color: rgb(248, 248, 248);
    border-radius: 4%;
    text-align: center;
}

.age {
    width: 100%;
    height: 12%;
    padding: 20rpx;
}

.age_bj {
    width: 28%;
    margin-bottom: 20rpx;
    border-radius: 4%;
    background-color: rgb(248, 248, 248);
    text-align: center;
}

.zh {
    width: 100%;
    height: 10%;
    padding: 20rpx;
}

.zh_bj {
    width: 45%;
    border-radius: 4%;
    margin-bottom: 20rpx;
    background-color: rgb(248, 248, 248);
    text-align: center;
}

.btn {
    width: 60%;
    height: 5%;
    background: linear-gradient(to right, #4fb784, #a4d79f);
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
}

.xzzt {
    color: #4fb784;
    background-color: #fff;
    border-radius: 4%;
}
</style>
